package models

import (
	"gitee.com/sansaniot/ssiot-core/httpmvc/model"

	"ssnotify/common/dto"
	cDto "ssnotify/common/dto"
	"ssnotify/internal/notify/models/query"
)

type NotifyTemplate struct {
	Id         string          `json:"id" gorm:"primaryKey;type:varchar(64)"`
	Type       string          `json:"type" gorm:"type:varchar(10);comment:通知类型"`
	Content    string          `json:"content" gorm:"type:longtext;comment:模板内容"`
	Name       string          `json:"name" gorm:"type:varchar(64);comment:模板名"`
	CreatorId  string          `json:"creatorId" gorm:"type:varchar(64);comment:创建人id"`
	CreateTime *cDto.LocalTime `json:"createTime" gorm:"type:timestamptz(6);comment:创建时间"`
	UpdateTime *cDto.LocalTime `json:"updateTime" gorm:"type:timestamptz(6);comment:更新时间"`
	AgencyId   string          `json:"agencyId" gorm:"type:varchar(64);comment:机构用户id"`
	model.Model
}

func (NotifyTemplate) TableName() string {
	return "sys_notify_template"
}

func (e *NotifyTemplate) Generate() *NotifyTemplate {
	o := *e
	return &o
}

func (e *NotifyTemplate) FindNotifyTemplate(req *query.NotifyTemplateGetReq) (list []NotifyTemplate, err error) {
	list = make([]NotifyTemplate, 0)
	err = e.FindList(&list, dto.MakeCondition(req.GetNeedSearch()))
	return
}

func (e *NotifyTemplate) FindNotifyTemplateList(req *query.NotifyTemplateGetReq) (err error, result interface{}) {
	list := make([]NotifyTemplate, 0)
	var count int64
	if req.AgencyId != req.UserId {
		// 非租户查无数据
		if req.PageIndex > 0 && req.PageSize > 0 {
			result = &cDto.Page{
				Records:   list,
				Total:     count,
				PageSize:  req.GetPageSize(),
				PageIndex: req.GetPageIndex(),
				Pages:     (count + int64(req.GetPageSize()) - 1) / int64(req.GetPageSize()),
				Other:     nil,
			}
		} else {
			result = list
		}
		return
	}
	if req.PageIndex > 0 && req.PageSize > 0 {
		err = e.FindPage(&list, &count,
			cDto.MakeCondition(req.GetNeedSearch()),
			cDto.OrderDest("create_time", true, req.OrderBy),
			cDto.Paginate(req.GetPageSize(), req.GetPageIndex()),
		)
		result = &cDto.Page{
			Records:   list,
			Total:     count,
			PageSize:  req.GetPageSize(),
			PageIndex: req.GetPageIndex(),
			Pages:     (count + int64(req.GetPageSize()) - 1) / int64(req.GetPageSize()),
			Other:     nil,
		}
	} else {
		err = e.FindList(&list,
			cDto.MakeCondition(req.GetNeedSearch()),
			cDto.OrderDest("create_time", true, req.OrderBy),
		)
		result = list
	}
	return
}
